package com.awesome.spring.netty.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: awesome-spring
 * @description: 聊天处理器类
 * @author: Alex Wu
 * @createDate: 2025-03-14 16:10
 **/
public class SimpleChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Map<String, Channel> userChannelMap = new ConcurrentHashMap<>();
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String message = textWebSocketFrame.text();
        System.out.println("Received message: " + message);
        userChannelMap.forEach((username, channel) -> {
            channel.writeAndFlush(new TextWebSocketFrame("Echo: "+ message));
        });
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        userChannelMap.put(ctx.channel().id().asShortText(), ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        userChannelMap.remove(ctx.channel().id().asShortText());
    }
}
